package fragment;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mywood.LoginActivity;
import com.example.mywood.R;
import com.example.mywood.SearchActivity;
import com.example.mywood.ZhantingGoodsActivity;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.ListviewAdapter;
import adapter.ShaixuanAllAdapter;
import adapter.ShowRoomRecyclerViewAdapter;
import bean.ContentDataBean;
import bean.ShowRoomAllDataBean;
import bean.ZhantingListBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.PullLoadMoreRecyclerView;
import util.DensityUtil;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;

public class ZhantingFragment extends Fragment {

    private View view;
    private Context mcontext;
    private LinearLayout ll_nodata;
    private LinearLayout ll_search;
    private MyApp myapp;
    private String token;
    private List<ZhantingListBean.DataBean> temzhantingList = new ArrayList<>();
    private PopupWindow mPopupWindow;
    private int heightPixels;
    private String nameStr;
    private String phoneStr;
    private String imageStr;
    private String start_timeStr;
    private String end_timeStr;
    private String contentStr;
    private String locationStr;

    private PackageManager mPackageManager;
    private static List<String> mPackageNames = new ArrayList<>();
    private static final String GAODE_PACKAGE_NAME = "com.autonavi.minimap";
    private static final String BAIDU_PACKAGE_NAME = "com.baidu.BaiduMap";
private double currLocationX = 0.0;
private double currLocationY = 0.0;
private double locationX = 0.0;
private double locationY = 0.0;
private String storeName = "北京饭店";

//    private double currLocationX;//起点 纬度
//    private double currLocationY;//起点 经度
//    private double locationX;//终点 纬度
//    private double locationY;//终点 经度
//    private String storeName;//地点名称
    private String url;
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private LinearLayout ll_dataall;
    private List<ShowRoomAllDataBean> alldatalist = new ArrayList<>();
    private List<ShowRoomAllDataBean> temgoodsList = new ArrayList<>();
    private ListviewAdapter allDataAdapter;
    private PullLoadMoreRecyclerView rclv_showroom;
    private ShowRoomRecyclerViewAdapter adapter;
    private int width;
    private int pagesize = 10;
    private int page = 1;
    private View bottomView;
    private CustomProgressDialog customProgressDialog;
    private ContentDataBean.DataBean textContent;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_zhanting, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        getScreenDen();
        sharedPreferences = mcontext.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        mPackageManager = mcontext.getPackageManager();
        EventBus.getDefault().register(this);

        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        customProgressDialog.show();
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);

        initView();
        initLin();
        getAllData();
//        getZhantingListData();

        return view;

    }
    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        MyLog.e("message--new--order", message);
        if ("跳转地图导航".equals(message)) {
            locationStr = event.getType();
            MyLog.e("type--new--order", locationStr);
            if(haveGaodeMap()){//如果安装高德APP
                openGaodeMapToGuide();//打开高德APP
            } else {//否则 打开浏览器
                openBrowserToGuide();
            }
        }else if ("跳转商品链接".equals(message)){
            String type = event.getType();
            MyLog.e("name--new--order", type);
            Intent intent = new Intent(mcontext, ZhantingGoodsActivity.class);
            intent.putExtra("ztname",type);
            startActivity(intent);
        }

    }
    private void initView() {
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        rclv_showroom = view.findViewById(R.id.rclv_showroom);
        adapter = new ShowRoomRecyclerViewAdapter(alldatalist, mcontext, myapp,width, textContent);
        setHeader(rclv_showroom);
        rclv_showroom.setAdapter(adapter);
        rclv_showroom.setGridLayout(2);
        rclv_showroom.setRefreshing(true);
        rclv_showroom.cancleAnimal();
        ll_nodata = view.findViewById(R.id.ll_nodata);
        ll_search = view.findViewById(R.id.ll_search);

        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_shou_phone = view.findViewById(R.id.tv_shou_phone);
        TextView tv_opentime = view.findViewById(R.id.tv_opentime);
        TextView tv_address = view.findViewById(R.id.tv_address);
        TextView tv_goods_link = view.findViewById(R.id.tv_goods_link);
        TextView tv_nodata = view.findViewById(R.id.tv_nodata);

//        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_title.setText(textContent.getShowroom());
//            tv_nodata.setText(textContent.getNodata());
        }


    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {


        //底部加载更多
        bottomView = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }

    private void initLin() {
        ll_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("activityType","");
                intent.putExtra("showroom","");
                startActivity(intent);
            }
        });
        rclv_showroom.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                rclv_showroom.setPullLoadMoreCompleted();
            }

            @Override
            public void onLoadMore() {
                customProgressDialog.show();
                page++;
                getAllData();
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });

    }

      int checkid = 0;



    /**
     * 请求头部筛选标题
     */
    private void getZhantingListData() {
        temzhantingList.clear();
        String url = myapp.getWebConfig() + "/api/index/gallery_list";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temzhantingList = new Gson().fromJson(data.toString(), new TypeToken<List<ZhantingListBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    /**
     * 请求头部筛选标题
     */
    private void getZhantingData(String id) {
        String url = myapp.getWebConfig() + "/api/index/gallery_detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("gallery_id", id);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    nameStr = data.getString("name");
                    phoneStr = data.getString("phone");
                    imageStr = data.getString("image");
                    start_timeStr = data.getString("start_time");
                    end_timeStr = data.getString("end_time");
                    contentStr = data.getString("content");
//                    locationStr = data.getString("location");


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 请求头部筛选标题
     */
    private void getAllData() {
        temgoodsList.clear();
        String url = myapp.getWebConfig() + "/api/index/exhibition";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("page", page+"");
        paramsMap.put("size", pagesize+"");
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    for (int i = 0;i<data.length();i++){
                        ShowRoomAllDataBean bean = new ShowRoomAllDataBean();

                        bean.setId(data.getJSONObject(i).getString("id"));
                        bean.setContent(data.getJSONObject(i).getString("content"));
                        bean.setName(data.getJSONObject(i).getString("name"));
                        bean.setName_tran(data.getJSONObject(i).getString("name_tran"));
                        bean.setPhone(data.getJSONObject(i).getString("phone"));
                        bean.setWeigh(data.getJSONObject(i).getString("weigh"));
                        bean.setImage(data.getJSONObject(i).getString("image"));
                        bean.setStart_time(data.getJSONObject(i).getString("start_time"));
                        bean.setEnd_time(data.getJSONObject(i).getString("end_time"));
                        bean.setContent_tran(data.getJSONObject(i).getString("content_tran"));
                        bean.setLocation(data.getJSONObject(i).getString("location"));
                        bean.setLocation_tran(data.getJSONObject(i).getString("location_tran"));
                        bean.setKind_item_id(data.getJSONObject(i).getString("kind_item_id"));
                        bean.setUpdatetime(data.getJSONObject(i).getString("updatetime"));
                        bean.setCreatetime(data.getJSONObject(i).getString("createtime"));
                        temgoodsList.add(bean);
                    }



                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = (String) msg.obj;
                    Toast.makeText(mcontext, str, Toast.LENGTH_LONG).show();
                    if (str.contains("当前展厅不存在")){
                        ll_nodata.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    Toast.makeText(mcontext, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    if (temzhantingList.size() > 0){
                        String zhanname = temzhantingList.get(0).getName();
//                        getZhantingData(temzhantingList.get(0).getId()+"");
                    }else{
                        ll_nodata.setVisibility(View.VISIBLE);
                    }

                    break;
                case 3:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    ll_nodata.setVisibility(View.GONE);




                    break;
                case 4:

                    break;
                case 11:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
                case 5:
//                    rclv_showroom.setPullLoadMoreCompleted();
//                    adapter.setDatas(alldatalist);

                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }

                    if (page == 1){
                        rclv_showroom.scrollToTop();
                        adapter.notifyDataSetChanged();
                    }
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    adapter.setDatas(temgoodsList);
                    MyLog.e("页码",page+"   页码");
                    if (page == 1) {
                        alldatalist.clear();
                    }
                    alldatalist.addAll(temgoodsList);
                    adapter.setDatas(alldatalist);
//                    loadLlay.removeAllViews();
                    rclv_showroom.setPullLoadMoreCompleted();
                    if (alldatalist.size() == 0){
//                        Toast.makeText(mcontext,getString(R.string.nodata),Toast.LENGTH_LONG).show();
                        ll_nodata.setVisibility(View.VISIBLE);
                        rclv_showroom.setVisibility(View.GONE);
                    }else{
                        ll_nodata.setVisibility(View.GONE);
                        rclv_showroom.setVisibility(View.VISIBLE);
                    }


                    break;
            }
        }
    };
private boolean islogin = false;
    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }
    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("展厅","onResume");
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("展厅","onHiddenChanged     "+hidden);
        if (!hidden){
            checkid = 0;
//            getZhantingListData();
            getAllData();
        }




    }



    /**
     * 打开高德地图
     * https://lbs.amap.com/api/amap-mobile/guide/android/route
     */
    private void openGaodeMapToGuide() {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            MyLog.i("高德定位：","经度："+currLocationY+" ,纬度："+currLocationX);
            if (currLocationX == 0.0 || currLocationY == 0.0){
                url = "androidamap://route?sourceApplication=amap"+"&dname="+locationStr+"&dev=0&t=1";
            }else {
                url = "androidamap://route?sourceApplication=amap&"
                        +"&dname="+locationStr+"&dev=0&t=1";
            }



            Uri uri = Uri.parse(url);
            //将功能Scheme以URI的方式传入data
            intent.setData(uri);
            //启动该页面即可
            startActivity(intent);

        }catch (Exception e){
            openBrowserToGuide();
        }
    }


    /**
     * 打开浏览器
     */
    private void openBrowserToGuide() {
        String url = "http://uri.amap.com/navigation?to=" +
                locationStr + "&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0";
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }





    public void initPackageManager(){
        mPackageManager = mcontext.getPackageManager();
        List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(0);
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                mPackageNames.add(packageInfos.get(i).packageName);
            }
        }
    }

    /**
     * 判断有无安装高德
     * @return
     */
    public boolean haveGaodeMap(){
        initPackageManager();
        return mPackageNames.contains(GAODE_PACKAGE_NAME);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
